package com.buddy.learn.javasource._io.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Buddy
 * @date 2021/5/16
 */
public class BIOServer {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9000);
            while (true) {
                System.out.println("等待连接...");
                Socket socket = serverSocket.accept();// 阻塞方法
                System.out.println("有客户端连接了...");
                new Thread(() -> {
                    try {
                        handler(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handler(Socket socket) throws IOException {
        System.out.println("thread id = " + Thread.currentThread().getId());
        byte[] bytes = new byte[1024];
        System.out.println("准备read...");
        // 接收客户端的数据，阻塞方法，没有数据可读时就阻塞
        int read = socket.getInputStream().read(bytes);
        if (read != -1) {
            System.out.println(new String(bytes, 0, read));
        }
        socket.getOutputStream().write("Hello BIO Client".getBytes());
        socket.getOutputStream().flush();


    }
}
